<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    body{
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .progress{
      position: relative;
      height: 25px;
      margin-top: 10px;
      text-align: center;
      border-radius: 5px;
      background-color: #d8d8d8;
      overflow: hidden;
    }
    .progress-show{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      z-index: 10;
    }
    .progress-bar{
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      background-color: cyan;
    }
    .submit-btn{
      width: auto;
      padding: 5px 10px;  
      text-align: center;
      margin:10px 0 0 75%;
      background-color: #f2f2f2;
      border-radius: 5px;
      user-select: none;
      cursor:pointer;
    }
  </style>
</head>
<body>

    <div class="container">
      <input type="file" id="file" name='file' enctype='multipart/form-data'>
      <div class="progress">
        <p class="progress-show">0%</p>
        <div class="progress-bar" style="width:0%"></div>
      </div>
      <div class="submit-btn">提交</div>
    </div>
    

  <script>
    let file=document.querySelector('#file')
    let bar=document.querySelector('.progress-bar')
    let progress=document.querySelector('.progress-show')
    let btn=document.querySelector('.submit-btn')
    let formData=new FormData()
    console.log(file)
    file.onchange=function(){
      progress.innerHTML='0%'
      bar.style.width='0%'
      formData.append('file',this.files[0])
      console.log(formData.get('file'))
    }

    btn.addEventListener('click',()=>{
      console.log('btn click to submit file')

      let xhr=new XMLHttpRequest()
      xhr.open('POST','http://localhost:3000/upload')
      xhr.upload.onprogress=function(e){
        console.log(e)
        bar.style.width=Math.round((e.loaded/e.total)*100)+'%'
        progress.innerHTML=Math.round((e.loaded/e.total)*100)+'%'
        console.log(Math.round((e.loaded/e.total)*100)+'%')
      }
      xhr.send(formData)

      xhr.onload=function(){
        if(xhr.status==200){
          console.log(xhr.responseText)
        }
      }
    })
  </script>
</body>
</html>